/*
Copyright (c) 2007,2007 Elizeu Nogueira da R. Jr.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.
    * Neither the name of the Elizeu Nogueira da R. Jr. nor the names of its 
      contributors may be used to endorse or promote products derived from this 
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


This package is based on HypersonicSQL, originally developed by Thomas Mueller.
and HSQLDB original developed by the HSQL Development Group
*/

package br.com.dreamsource.mobile.jmesql;

import br.com.dreamsource.mobile.jmesql.exceptions.SQLException;
import java.util.*;
import br.com.dreamsource.mobile.jmesql.jdbcStatement;
//import java.text.*;

/**
 * Class declaration
 *
 *
 * @version 1.0.0.1
 */
class Library {
    final static String sNumeric[] = {
	"COT", "br.com.dreamsource.mobile.jmesql.Library.cot", 
        "LOG10", "br.com.dreamsource.mobile.jmesql.Library.log10", 
        "MOD", "br.com.dreamsource.mobile.jmesql.Library.mod", 
        "PI", "br.com.dreamsource.mobile.jmesql.Library.pi", 
        "ROUND", "br.com.dreamsource.mobile.jmesql.Library.round", 
        "SIGN", "br.com.dreamsource.mobile.jmesql.Library.sign", 
        "TRUNCATE", "br.com.dreamsource.mobile.jmesql.Library.truncate",
	"BITAND", "br.com.dreamsource.mobile.jmesql.Library.bitand", 
        "BITOR", "br.com.dreamsource.mobile.jmesql.Library.bitor", 
        "ROUNDMAGIC", "br.com.dreamsource.mobile.jmesql.Library.roundMagic",
    };

    final static String sString[] = {
	"ASCII", "br.com.dreamsource.mobile.jmesql.Library.ascii", "CHAR",
	"br.com.dreamsource.mobile.jmesql.Library.character", "CONCAT", "br.com.dreamsource.mobile.jmesql.Library.concat",
	"DIFFERENCE", "br.com.dreamsource.mobile.jmesql.Library.difference", "INSERT",
	"br.com.dreamsource.mobile.jmesql.Library.insert", "LCASE", "br.com.dreamsource.mobile.jmesql.Library.lcase", "LEFT",
	"br.com.dreamsource.mobile.jmesql.Library.left", "LENGTH", "br.com.dreamsource.mobile.jmesql.Library.length",
	"LOCATE", "br.com.dreamsource.mobile.jmesql.Library.locate", "LTRIM",
	"br.com.dreamsource.mobile.jmesql.Library.ltrim", "REPEAT", "br.com.dreamsource.mobile.jmesql.Library.repeat",
	"REPLACE", "br.com.dreamsource.mobile.jmesql.Library.replace", "RIGHT",
	"br.com.dreamsource.mobile.jmesql.Library.right", "RTRIM", "br.com.dreamsource.mobile.jmesql.Library.rtrim",
	"SOUNDEX", "br.com.dreamsource.mobile.jmesql.Library.soundex", "SPACE",
	"br.com.dreamsource.mobile.jmesql.Library.space", "SUBSTR","org.hsql.Library.substring",
        "SUBSTRING", "br.com.dreamsource.mobile.jmesql.Library.substring",
	"UCASE", "br.com.dreamsource.mobile.jmesql.Library.ucase", "LOWER", "br.com.dreamsource.mobile.jmesql.Library.lcase",
	"UPPER", "br.com.dreamsource.mobile.jmesql.Library.ucase"
    };
    final static String sTimeDate[] = {
	"CURDATE", "br.com.dreamsource.mobile.jmesql.Library.curdate", "CURTIME",
	"br.com.dreamsource.mobile.jmesql.Library.curtime", "DAYNAME", "br.com.dreamsource.mobile.jmesql.Library.dayname",
	"DAYOFMONTH", "br.com.dreamsource.mobile.jmesql.Library.dayofmonth", "DAYOFWEEK",
	"br.com.dreamsource.mobile.jmesql.Library.dayofweek", "DAYOFYEAR",
	"br.com.dreamsource.mobile.jmesql.Library.dayofyear", "HOUR", "br.com.dreamsource.mobile.jmesql.Library.hour",
	"MINUTE", "br.com.dreamsource.mobile.jmesql.Library.minute", "MONTH",
	"br.com.dreamsource.mobile.jmesql.Library.month", "MONTHNAME", "br.com.dreamsource.mobile.jmesql.Library.monthname",
	"NOW", "br.com.dreamsource.mobile.jmesql.Library.now", "QUARTER", "br.com.dreamsource.mobile.jmesql.Library.quarter",
	"SECOND", "br.com.dreamsource.mobile.jmesql.Library.second", "WEEK", "br.com.dreamsource.mobile.jmesql.Library.week",
	"YEAR", "br.com.dreamsource.mobile.jmesql.Library.year",
    };
    final static String sSystem[] = {
	"DATABASE", "br.com.dreamsource.mobile.jmesql.Library.database", "USER",
	"br.com.dreamsource.mobile.jmesql.Library.user", "IDENTITY", "br.com.dreamsource.mobile.jmesql.Library.identity"
    };

    static void register(Hashtable h) {
	register(h, sNumeric);
	register(h, sString);
	register(h, sTimeDate);
	register(h, sSystem);
    }

    private static void register(Hashtable h, String s[]) {
	for (int i = 0; i < s.length; i += 2) {
	    h.put(s[i], s[i + 1]);
	}
    }

    static Random rRandom = new Random();

    public static int mod(int i1, int i2) {
	return i1 % i2;
    }

    public static int bitand(int i, int j) {
	return i & j;
    }

    public static int bitor(int i, int j) {
	return i | j;
    }

    public static Integer ascii(String s) {
	if (s == null || s.length() == 0) {
	    return null;
	}
	return new Integer(s.charAt(0));
    }

    public static String character(int code) {
	return "" + (char) code;
    }
    
    public static String concat(String s1, String s2) {
	if (s1 == null) {
	    if (s2 == null) {
		return null;
	    }

	    return s2;
	}

	if (s2 == null) {
	    return s1;
	}

	return s1 + s2;
    }

    public static int difference(String s1, String s2) {

	if (s1 == null || s2 == null) {
	    return 0;
	}
	s1 = soundex(s1);
	s2 = soundex(s2);
	int len1 = s1.length(), len2 = s2.length();
	int e = 0;
	for (int i = 0; i < 4; i++) {
	    if (i >= len1 || i >= len2 || s1.charAt(i) != s2.charAt(i)) {
		e++;
	    }
	}

	return e;
    }

    public static String insert(String s1, int start, int length, String s2) {
	if (s1 == null) {
	    return s2;
	}

	if (s2 == null) {
	    return s1;
	}

	int len1 = s1.length();
	int len2 = s2.length();

	start--;

	if (start < 0 || length <= 0 || len2 == 0 || start > len1) {
	    return s1;
	}

	if (start + length > len1) {
	    length = len1 - start;
	}

	return s1.substring(0, start) + s2 + s1.substring(start + length);
    }

    public static String lcase(String s) {
	return s == null ? null : s.toLowerCase();
    }

    public static String left(String s, int i) {
	return s == null ? null
	       : s.substring(0,
			     (i < 0 ? 0 : i < s.length() ? i : s.length()));
    }

    public static int length(String s) {
	return (s == null || s.length() < 1) ? 0 : s.length();
    }

    public static int locate(String search, String s, Integer start) {
	if (s == null || search == null) {
	    return 0;
	}

	int i = start == null ? 0 : start.intValue() - 1;

	return s.indexOf(search, i < 0 ? 0 : i) + 1;
    }

    public static String ltrim(String s) {
	if (s == null) {
	    return s;
	}

	int len = s.length(), i = 0;

	while (i < len && s.charAt(i) <= ' ') {
	    i++;
	}

	return i == 0 ? s : s.substring(i);
    }

    public static String repeat(String s, int i) {
	if (s == null) {
	    return null;
	}

	StringBuffer b = new StringBuffer();

	while (i-- > 0) {
	    b.append(s);
	}

	return b.toString();
    }

    public static String replace(String s, String replace, String with) {
	if (s == null || replace == null) {
	    return s;
	}

	if (with == null) {
	    with = "";
	}

	StringBuffer b = new StringBuffer();
	int	     start = 0;
	int	     lenreplace = replace.length();

	while (true) {
	    int i = s.indexOf(replace, start);

	    if (i == -1) {
		b.append(s.substring(start));

		break;
	    }

	    b.append(s.substring(start, i - start));
	    b.append(with);

	    start = i + lenreplace;
	}

	return b.toString();
    }

    public static String right(String s, int i) {
	if (s == null) {
	    return null;
	}

	i = s.length() - i;

	return s.substring(i < 0 ? 0 : i < s.length() ? i : s.length());
    }

    public static String rtrim(String s) {
	if (s == null) {
	    return s;
	}

	int i = s.length() - 1;

	while (i >= 0 && s.charAt(i) <= ' ') {
	    i--;
	}

	return i == s.length() ? s : s.substring(0, i + 1);
    }

    public static String soundex(String s) {
	if (s == null) {
	    return s;
	}

	s = s.toUpperCase();

	int  len = s.length();
	char b[] = new char[4];

	b[0] = s.charAt(0);

	int j = 1;

	for (int i = 1; i < len && j < 4; i++) {
	    char c = s.charAt(i);

	    if ("BFPV".indexOf(c) != -1) {
		b[j++] = '1';
	    } else if ("CGJKQSXZ".indexOf(c) != -1) {
		b[j++] = '2';
	    } else if (c == 'D' || c == 'T') {
		b[j++] = '3';
	    } else if (c == 'L') {
		b[j++] = '4';
	    } else if (c == 'M' || c == 'N') {
		b[j++] = '5';
	    } else if (c == 'R') {
		b[j++] = '6';
	    }
	}

	return new String(b, 0, j);
    }

    public static String space(int i) {
	if (i < 0) {
	    return null;
	}

	char c[] = new char[i];

	while (i > 0) {
	    c[--i] = ' ';
	}

	return new String(c);
    }

    public static String substring(String s, int start, Integer length) {
	if (s == null) {
	    return null;
	}

	int len = s.length();

	start--;
	start = start > len ? len : start;

	if (length == null) {
	    return s.substring(start);
	} else {
	    int l = length.intValue();

	    return s.substring(start, start + l > len ? len : l);
	}
    }

    public static String ucase(String s) {
	return s == null ? null : s.toUpperCase();
    }

    public static java.util.Date curdate() {
	return new java.util.Date(System.currentTimeMillis());
    }

    public static String database(jdbcConnection conn) throws SQLException {
	jdbcStatement stat = conn.createStatement();
	String    s =
	    "SELECT Value FROM SYSTEM_CONNECTIONINFO WHERE KEY='DATABASE'";
	jdbcResultSet r = stat.executeQuery(s);

	r.next();

	return r.getString(1);
    }

    public static String user(jdbcConnection conn) throws SQLException {
	jdbcStatement stat = conn.createStatement();
	String    s =
	    "SELECT Value FROM SYSTEM_CONNECTIONINFO WHERE KEY='USER'";
	jdbcResultSet r = stat.executeQuery(s);

	r.next();

	return r.getString(1);
    }

    public static int identity(jdbcConnection conn) throws SQLException {
	jdbcStatement stat = conn.createStatement();
	String    s =
	    "SELECT VALUE FROM SYSTEM_CONNECTIONINFO WHERE KEY='IDENTITY'";
	jdbcResultSet r = stat.executeQuery(s);

	r.next();

	return r.getInt(1);
    }

}
